package com.oc.mba.service.impl;

import java.sql.Timestamp;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.oc.mba.dao.DeviceMessageDAO;
import com.oc.mba.dao.MessageDAO;
import com.oc.mba.entity.DeviceMessageEntity;
import com.oc.mba.entity.MessageEntity;
import com.oc.mba.entity.OcDevices;
import com.oc.mba.service.MessageService;
import com.oc.mba.util.CommConsts;
import com.oc.mba.util.CommDateUtil;
import com.oc.mba.util.CommLog;

@Service
public class MessageServiceImpl implements MessageService {

	private static final CommLog logger = new CommLog(MessageServiceImpl.class);

	@Autowired
	private MessageDAO messageDAO;
	
	@Autowired
	private DeviceMessageDAO deviceMessageDAO;
	
	@Override
	public List<MessageEntity> listAllMessage() {
		logger.debug("list all Message.");
		List<MessageEntity> messageList = messageDAO.finAllMessage();
		return messageList;
	}
	
	@Override
	public List<DeviceMessageEntity> listAllDeviceMessage(Integer deviceID) {
		logger.debug("list all Device Message.");
		List<DeviceMessageEntity> messageList = deviceMessageDAO.findAllDeviceMessage(deviceID);
		return messageList;
	}

	/**
	 * 创建每日一练消息
	 */
	@Override
	public void createDailyMessage(OcDevices device) {
		if (!hasDailyMessage(device)) {
			Timestamp timestamp = new Timestamp(System.currentTimeMillis());
			DeviceMessageEntity dailyMessage = new DeviceMessageEntity();
			dailyMessage.setDeviceId(device.getId());
			dailyMessage.setMsgContent("MBA综合宝典邀请您参加今日[2012-12-09][每日一练]");
			dailyMessage.setMsgExpire(CommConsts.DbValue.MSG_NEED_EXPIRE);
			dailyMessage.setMsgExpireTime(timestamp);
			dailyMessage.setMsgFeedback(CommConsts.DbValue.MSG_FEEDBACK_NO);
			dailyMessage.setMsgTime(timestamp);
			dailyMessage.setMsgTitle("MBA综合宝典每日一练[2012-12-09]");
			dailyMessage.setMsgType(CommConsts.DbValue.MSG_TYPE_DAILY);
			// 保存每日一练消息
			deviceMessageDAO.save(dailyMessage);
		}
	}
	
	/**
	 * 是否已经生成每日一练消息
	 */
	@Override
	public boolean hasDailyMessage(OcDevices device) {
		// 当前日期的零点
		Timestamp tNow = CommDateUtil.today();
		// 明天零点
		Timestamp tNext = CommDateUtil.dateAdditionDay(tNow, 1);
		List<DeviceMessageEntity> messageList = deviceMessageDAO.findDeviceMessage(device.getId(), CommConsts.DbValue.MSG_TYPE_DAILY, tNow, tNext);
		if (messageList!=null && messageList.size() > 0) {
			logger.info(CommDateUtil.DateToString(tNow) + " has bean created daily message");
			return true;
		}
		else {
			logger.info(CommDateUtil.DateToString(tNow) + " hasn't created daily message");
			return false;
		}
	}
}
